package touro.mancala.master;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;

public class SlaveSocketHandler implements Runnable {

	private static final Logger logger = Logger.getLogger(SlaveSocketHandler.class.getName());

	private Socket slave;
	private Server server;
	
	public SlaveSocketHandler( Server server, Socket toSlave ) {
		this.slave = toSlave;
		this.server = server;
	}
	
	public void run() {
		
		InputStream in;
		BufferedReader reader;
		try {
			in = slave.getInputStream();
			reader = new BufferedReader(new InputStreamReader(in));
		} catch (IOException e1) {
			e1.printStackTrace();
			return;
		}

		while (true) {
			try {
				String line = reader.readLine();//gets this line from the slave
				logger.log(Level.INFO, "Read line: " + line);

				StringTokenizer tokenizer = new StringTokenizer(line);
				//parse out all of the parts of the line 
				// TODO: complete this
				Response response = new Response(slave, 
						Integer.parseInt(tokenizer.nextToken()), 
						Integer.parseInt(tokenizer.nextToken()), 
						Integer.parseInt(tokenizer.nextToken()));
				
				
				server.getResponseManager().addResponse(response);
				
			} catch (Exception e) {
				//e.printStackTrace();
			}

		}
		
		
	}

}
